import { Component } from '@angular/core';
import { FormLayout, TableWidthConfig, DValidateRules, DialogService } from '@devui';
import { ReviewRolesService } from 'src/app/@core/services/ReviewRoles/review-roles.service';
import { AttachmentComponent } from 'src/app/@shared/components/attachment/attachment.component';
import { SelectMaterialComponent } from 'src/app/@shared/components/select-material/select-material.component';
import { SelectSupplierComponent } from 'src/app/@shared/components/select-supplier/select-supplier.component';
import { SelectUserComponent } from 'src/app/@shared/components/select-user/select-user.component';
import { environment } from 'src/environments/environment';
import { Router } from '@angular/router';
import { UserService } from 'src/app/@core/services/user/user.service';
import { PurchaseService } from 'src/app/@core/services/purchase/purchase.service';
import { CustomerService } from 'src/app/@core/services/customer/customer.service';
import { SupplierPriceService } from 'src/app/@core/services/supplierPrice/supplier-price.service';
import { EncodeRulesService } from 'src/app/@core/services/encoderRule/encode-rules.service';
import { StorehouseService } from 'src/app/@core/services/storehouse/storehouse.service';

// 报销单数据模型
export interface IngredientReimbursement {
  reimbursementId: number | null;
  reimbursementNum: string;
  requestDate: Date;
  requestBy: string;
  requestById: number;
  department: string;
  departmentId: number;
  supplierName: string;
  supplierId: number;
  supplierFullName: string;
  supplierContact: string;
  supplierContactId: number;
  totalAmount: number;
  taxAmount: number;
  totalAmountWithoutTax: number;
  status: string;
  isClosed: boolean;
  attachment: string;
  remark: string;
  creator: string;
  createDate: Date | null;
  reimbursementDetails: IngredientReimbursementDetail[];
}
// 报销明细数据模型
export interface IngredientReimbursementDetail {
  itemId: number | null;
  ingredientCode: string;
  ingredientName: string;
  specification: string;
  description: string;
  unit: string;
  quantity: number;
  unitPrice: number;
  totalAmount: number;
  purchaseDate: string;
  invoiceNum: string;
  storageLocation: string;
  remark: string;
  materialId: number;
  image: string;
}
@Component({
  selector: 'app-ingredient-reimbursement-approval-add',
  templateUrl: './ingredient-reimbursement-approval-add.component.html',
  styleUrls: ['./ingredient-reimbursement-approval-add.component.scss']
})
export class IngredientReimbursementApprovalAddComponent {
  Math = Math;
  msgs: Array<Object> = [];
  UrlHead: any = environment.modifiedApiUrl;
  layoutDirection: FormLayout = FormLayout.Horizontal;
  isSubmit: boolean = false;
  tableWidthConfig: TableWidthConfig[] = [
    {
      field: '操作',
      width: '150px',
    },
    {
      field: '编码',
      width: '150px',
    },
    {
      field: '图片',
      width: '150px',
    },
    {
      field: '名称',
      width: '150px',
    },
    {
      field: '规格',
      width: '150px',
    },
    {
      field: '描述',
      width: '150px',
    },
    {
      field: '单位',
      width: '150px',
    },
    {
      field: '数量',
      width: '150px',
    },
    {
      field: '单价',
      width: '200px',
    },
    {
      field: '总金额',
      width: '200px',
    },
    {
      field: '采购日期',
      width: '150px',
    },
    {
      field: '发票号',
      width: '200px',
    },
    {
      field: '存储位置',
      width: '150px',
    },
    {
      field: '备注',
      width: '250px',
    }
  ]; //表格宽度配置
  customerContact: any;
  loadData: boolean;
  ingredientReimbursement: IngredientReimbursement = {
    reimbursementId: null, // 报销单ID
    reimbursementNum: '', // 报销单号
    requestDate: new Date(), // 申请日期
    requestBy: '', // 申请人
    requestById: 0, // 申请人ID
    department: '', // 部门
    departmentId: 0, // 部门ID
    supplierName: '', // 供应商名称
    supplierId: 0, // 供应商ID
    supplierFullName: '', // 供应商全称
    supplierContact: '', // 供应商联系人
    supplierContactId: 0, // 供应商联系人ID
    totalAmount: 0, // 总金额
    taxAmount: 0, // 税额
    totalAmountWithoutTax: 0, // 不含税总金额
    status: '待审批', // 状态
    isClosed: false, // 是否结案
    attachment: '', // 附件
    remark: '', // 备注
    creator: '', // 制单人
    createDate: null, // 制单日期
    reimbursementDetails: [
      {
        itemId: null, // 明细行ID
        ingredientCode: '', // 编码
        ingredientName: '', // 名称
        specification: '', // 规格
        description: '', // 描述
        unit: '', // 单位
        quantity: 0, // 数量
        unitPrice: 0, // 单价
        totalAmount: 0, // 总金额
        purchaseDate: '', // 采购日期
        invoiceNum: '', // 发票号
        storageLocation: '', // 存储位置
        remark: '', // 备注
        materialId: 0, // 物料ID
        image: '', // 图片
      },
    ],
  };
  ingredientReimbursementRules: { [key: string]: DValidateRules } = {
    reimbursementNum: {
      messageShowType: 'text',
      validators: [
        { required: true, message: '*报销单号不能为空' },
        { minlength: 2, message: '*报销单号长度至少为2' },
        { maxlength: 40, message: '*报销单号长度至多为40' },
        { pattern: /^[^\s]*$/, message: '*报销单号不能包含空格' },
      ],
    },
    requestBy: {
      messageShowType: 'text',
      validators: [{ required: true, message: '*申请人不能为空' }],
    },
    supplierName: {
      messageShowType: 'text',
      validators: [{ required: true, message: '*供应商不能为空' }],
    },
    ingredientCode: {
      messageShowType: 'text',
      validators: [{ required: true, message: '*编码不能为空' }],
    },
    requestDate: {
      messageShowType: 'text',
      validators: [{ required: true, message: '*申请日期不能为空' }],
    },
    quantity: {
      messageShowType: 'text',
      validators: [{ required: true, message: '*数量不能为空' }],
    },
    unitPrice: {
      messageShowType: 'text',
      validators: [{ required: true, message: '*单价不能为空' }],
    },
    invoiceNum: {
      messageShowType: 'text',
      validators: [{ required: true, message: '*发票号不能为空' }],
    },
  };
  options = [
    { label: '检验', value: true },
    { label: '不检验', value: false }
  ]
  supplyContactOption = []; // 供应商联系人
  supplyContact = {}; //供应商联系人
  fujianNumber: any = 0;
  constructor(
    private DialogService: DialogService,
    private Router: Router,
    private UserService: UserService,
    private PurchaseService: PurchaseService,
    private CustomerService: CustomerService,
    private SupplierPriceService: SupplierPriceService,
    private EncodeRulesService: EncodeRulesService,
    private StorehouseService: StorehouseService,
    private ReviewFlowService: ReviewRolesService
  ) { }
  ngOnInit(): void {
    this.EncodeRulesService.GenerateWarehouseCodeRule(
      '报销申请',
      '报销申请'
    ).subscribe((data: any) => {
      this.ingredientReimbursement.reimbursementNum = data;
    });
    const userinfoString = localStorage.getItem('userinfo');
    if (userinfoString) {
      this.ingredientReimbursement.creator = JSON.parse(userinfoString).username;
    }
  }
  selectMaterial(rowItem: any, dialogtype?: string) {
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '800px',
      backdropCloseable: true,
      data: '',
      title: '选择',
      content: SelectMaterialComponent,
      dialogtype: dialogtype,
      onClose: () => { },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            rowItem.materialId = results.modalContentInstance.selectData.partId;
            rowItem.ingredientCode = results.modalContentInstance.selectData.partNum;
            rowItem.ingredientName = results.modalContentInstance.selectData.partName;
            rowItem.unit = results.modalContentInstance.selectData.partUOM;
            rowItem.specification = results.modalContentInstance.selectData.partType;
            rowItem.image = results.modalContentInstance.selectData.fileURL;
            rowItem.description = results.modalContentInstance.selectData.description || '';

            this.StorehouseService.GetPartsAllInventory([
              rowItem.materialId,
            ]).subscribe((res: any) => {
              // 报销不需要实时库存
            });
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  showToast(type: any, summary: any, content: any) {
    switch (type) {
      default:
        this.msgs = [{ severity: type, summary: summary, content: content }];
    }
  } //提示框
  addRow() {
    this.ingredientReimbursement.reimbursementDetails.push({
      itemId: null,
      ingredientCode: '',
      ingredientName: '',
      specification: '',
      description: '',
      unit: '',
      quantity: 0,
      unitPrice: 0,
      totalAmount: 0,
      purchaseDate: '',
      invoiceNum: '',
      storageLocation: '',
      remark: '',
      materialId: 0,
      image: ''
    });
  } //添加行
  deleteRow(index: number) {
    this.ingredientReimbursement.reimbursementDetails.splice(index, 1);
    if (this.ingredientReimbursement.reimbursementDetails.length == 0) {
      this.addRow();
    }
    this.calculateTotalAmount();
  }
  isStartApproval: boolean = false;
  isStartApprovalChange() {
    this.isStartApproval = true;
  }
  submit($event: any) {
    if ($event.valid) {
      if (!this.validateReimbursement(this.ingredientReimbursement)) {
        return;
      }
      this.ingredientReimbursement.createDate = new Date();
      this.ingredientReimbursement.reimbursementDetails.forEach((item) => {
        // 设置报销单号到明细行
      });
      console.log(this.ingredientReimbursement);

      // 调用报销单API (需要在PurchaseService中添加)
      // TODO: 需要在PurchaseService中添加addIngredientReimbursement方法
      console.log('提交报销申请数据:', this.ingredientReimbursement);

      // 模拟API调用成功
      setTimeout(() => {
        this.isSubmit = false;
        if (this.isStartApproval) {
          this.ReviewFlowService.StartApprovalFlow('报销审核流配置', [
            this.ingredientReimbursement.reimbursementNum,
          ]).subscribe(
            (data: any) => {
              this.showToast('success', '成功', '流程发起成功');
              setTimeout(() => {
                this.cancel();
              }, 1000);
            },
            (error: any) => {
              this.showToast('error', '失败', error.error);
              setTimeout(() => {
                this.cancel();
              }, 1000);
            }
          );
        } else {
          this.showToast('success', '成功', '提交成功');
          setTimeout(() => {
            this.cancel();
          }, 1000);
        }
      }, 1000);
    } else {
      this.showToast('warn', '错误', '请检查表单是否填写正确');
    }
  }
  getImagesArray(fileURL: string): string[] {
    let urls = fileURL.split(',');
    urls = urls.map((url) => environment.modifiedApiUrl + url);
    return urls;
  }
  cancel() {
    this.Router.navigateByUrl('/pages/purchase/ingredient-reimbursement-approval');
  }
  fujian(dialogtype?: string) {
    const results = this.DialogService.open({
      title: '报销附件',
      width: '800px',
      backdropCloseable: false,
      data: {
        data: '报销附件',
        urls: this.ingredientReimbursement.attachment ? [this.ingredientReimbursement.attachment] : [],
      },
      content: AttachmentComponent,
      dialogtype: dialogtype,
      onClose: () => { },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.ingredientReimbursement.attachment = results.modalContentInstance.urls[0] || '';
            this.fujianNumber = this.ingredientReimbursement.attachment ? 1 : 0;
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  validateReimbursement(ingredientReimbursement: IngredientReimbursement): boolean {
    for (const [index, item] of ingredientReimbursement.reimbursementDetails.entries()) {
      if (!item.ingredientCode) {
        this.showToast('warn', '错误', `第${index + 1}行编码不能为空`);
        return false;
      }
      if (item.quantity <= 0) {
        this.showToast('warn', '错误', `第${index + 1}行数量必须大于0`);
        return false;
      }
      if (item.unitPrice <= 0) {
        this.showToast('warn', '错误', `第${index + 1}行单价必须大于0`);
        return false;
      }
      if (!item.invoiceNum) {
        this.showToast('warn', '错误', `第${index + 1}行发票号不能为空`);
        return false;
      }
    }
    return true;
  }
  selectUser() {
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '800px',
      backdropCloseable: true,
      data: '',
      title: '选择申请人',
      content: SelectUserComponent,
      onClose: () => { },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.ingredientReimbursement.requestBy =
              results.modalContentInstance.selectData.name;
            this.ingredientReimbursement.requestById =
              results.modalContentInstance.selectData.id;
            this.UserService.GetDepartmentById(
              results.modalContentInstance.selectData.departmentId
            ).subscribe((res: any) => {
              this.ingredientReimbursement.department = res.name;
              this.ingredientReimbursement.departmentId = res.departmentId;
            });
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  selectDepartment() {
    if (!this.ingredientReimbursement.requestById) {
      this.showToast('warn', '请选择申请人', '请选择申请人');
    }
  }
  selectSupply(reset?: boolean) {
    const results = this.DialogService.open({
      id: 'Add',
      maxHeight: '400px',
      width: '800px',
      backdropCloseable: true,
      data: '',
      title: '选择供应商',
      content: SelectSupplierComponent,
      onClose: () => { },
      buttons: [
        {
          cssClass: 'stress',
          text: '确定',
          handler: ($event: Event) => {
            this.ingredientReimbursement.supplierName =
              results.modalContentInstance.selectData.supplyShortName;
            this.ingredientReimbursement.supplierId =
              results.modalContentInstance.selectData.supplyId;
            this.ingredientReimbursement.supplierFullName =
              results.modalContentInstance.selectData.supplyChineseName;
            this.supplyContactOption =
              results.modalContentInstance.selectData.supplyContacts;
            results.modalInstance.hide();
          },
        },
        {
          id: 'btn-cancel',
          cssClass: 'common',
          text: '取消',
          handler: ($event: Event) => {
            results.modalInstance.hide();
          },
        },
      ],
    });
  }
  selectSupplyContact($event: any) {
    this.ingredientReimbursement.supplierContactId = $event.supplyContactId;
    this.ingredientReimbursement.supplierContact = $event.supplyContactName;
  }
  // 数量变化计算
  quantityChange(rowitem: any, value: number) {
    rowitem.quantity = value;
    this.calculateAmount(rowitem);
  }

  // 单价变化计算
  unitPriceChange(rowitem: any, value: number) {
    rowitem.unitPrice = value;
    this.calculateAmount(rowitem);
  }

  // 计算单行金额
  calculateAmount(item: any): void {
    item.totalAmount = +(item.unitPrice * item.quantity).toFixed(2);
    this.calculateTotalAmount();
  }

  // 计算总金额
  calculateTotalAmount(): void {
    // 重置总计属性
    this.ingredientReimbursement.totalAmount = 0;
    this.ingredientReimbursement.totalAmountWithoutTax = 0;
    this.ingredientReimbursement.taxAmount = 0;

    // 遍历并累加各项值 (报销暂时不计算税额)
    this.ingredientReimbursement.reimbursementDetails.forEach((item) => {
      this.ingredientReimbursement.totalAmount += item.totalAmount;
      this.ingredientReimbursement.totalAmountWithoutTax += item.totalAmount; // 暂时等于总金额
    });

    // 保留2位小数
    this.ingredientReimbursement.totalAmount = parseFloat(
      this.ingredientReimbursement.totalAmount.toFixed(2)
    );
    this.ingredientReimbursement.totalAmountWithoutTax = parseFloat(
      this.ingredientReimbursement.totalAmountWithoutTax.toFixed(2)
    );
    this.ingredientReimbursement.taxAmount = parseFloat(
      this.ingredientReimbursement.taxAmount.toFixed(2)
    );
  }
}
